package handler

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/xuri/excelize/v2"
	"internal/api/logic/export"
	"internal/api/types"
	"internal/util"
	"net/http"
	"time"
)

func UserInfoExportHandler(c *gin.Context) {
	resp := &types.UserInfoExportResp{}
	resp.Code = -1
	resp.Msg = "server error"
	var req *types.UserInfoExportReq
	err := c.ShouldBindQuery(&req)
	if err != nil {
		resp.Msg = "http Params error"
		c.JSON(http.StatusBadRequest, resp)
		return
	}
	util.LogSrv.Debug("req=[%v]", req)
	// 解析token赋值给参数
	if token, ok := c.Get("token"); ok {
		req.Deviceno = token.(string)
	}
	// 实现业务逻辑
	f := excelize.NewFile()
	fileName := time.Now().Format("2006-01-02 15:04:05")
	defer func() {
		if err := f.Close(); err != nil {
			util.LogSrv.Error("Io resource release failed,err=%v", err)
		}
	}()
	// 获取写入数据
	err = export.GetUserInfoExport(f, req)
	if err != nil {
		resp.Msg = err.Error()
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  resp.Msg,
			"data": nil,
		})
		return
	}
	c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
	c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=%s.xlsx", fileName))
	// 将Excel文件内容写入HTTP响应体
	if _, err := f.WriteTo(c.Writer); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "Excel file Create error",
			"data": nil,
		})
		return
	}
	return
}
